package world.snowcrystal.dao.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class GrantedAuthorityTypeHandler extends BaseTypeHandler<List<GrantedAuthority>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<GrantedAuthority> parameter, JdbcType jdbcType) throws SQLException {
                StringBuilder buffer = new StringBuilder();
                for (GrantedAuthority grantedAuthority : parameter) {
                    buffer.append(grantedAuthority.getAuthority());
                }
                ps.setString(i, buffer.toString());

    }

    @Override
    public List<GrantedAuthority> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String result = rs.getString(columnName);
        if(StringUtils.hasText(result)) {
            throw new SQLException("Column '" + columnName + "' not found");
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(result);
    }

    @Override
    public List<GrantedAuthority> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        if(StringUtils.hasText(result)) {
            throw new SQLException("Column index '" + columnIndex + "' not found");
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(result);
    }

    @Override
    public List<GrantedAuthority> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        if(StringUtils.hasText(result)) {
            throw new SQLException("Column index '" + columnIndex + "' not found");
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(result);
    }
}
